import request from "@/utils/request";
// 上传图片
export function uploadApi(file) {
  let data = new FormData();
  data.append("file", file);
  return request({
    url: "api/File/UploadFile",
    method: "post",
    data: data,
    upload: true,
    timeout: 12000,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}


export const turnImgUrl = (Buffer) => {
  const arrayBuffer = new Uint8Array(Buffer);
  let src = "data:image/jpeg;base64," + arrayBufferToBase64(arrayBuffer); //这里需要添加前缀
  return src;
};
let arrayBufferToBase64 = (buffer) => {
  var binary = "";
  var bytes = new Uint8Array(buffer);
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
};

export async function getFileBase64(id) {
  return new Promise(async (resolve, reject) => {
    try {
      let res = await getPreview({ id });
      resolve(turnImgUrl(res));
    } catch (error) {
      console.log(error);
    }
  });
}

export function getBase64(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    let fileResult = "";
    reader.readAsDataURL(file);
    //开始转
    reader.onload = function () {
      fileResult = reader.result;
    };
    //转 失败
    reader.onerror = function (error) {
      reject(error);
    };
    //转 结束  咱就 resolve 出去
    reader.onloadend = function () {
      resolve(fileResult);
    };
  });
}

